package apis.amapv2.com.window;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Test2Activity extends AppCompatActivity {

    @BindView(R.id.ll1)
    LinearLayout ll1;//容器1
    @BindView(R.id.ll2)
    LinearLayout ll2;//容器2

    @BindView(R.id.btn_start)
    Button btnStart;//开始
    @BindView(R.id.btn1)
    Button btn1;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test2);

        initParamsAndValus();

        initView();
    }

    private void initParamsAndValus() {
        mContext = this;
    }

    private void initView() {
        ButterKnife.bind(this);
    }

    /**
     * 请求权限
     */
    private void requestPermission() {
        //在android6.0之前想要用WindowManager还蛮简单的
        //因為安全的問題,开发者要放这种功能需要使用者”认真”的同意,所以需要弹出对话框来同意。
        if (Build.VERSION.SDK_INT >= 23){
            //判断是否可以在App的上面进行绘制。
            if (! Settings.canDrawOverlays(Test2Activity.this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,10);
            } else {
                ll1.setVisibility(View.GONE);
                ll2.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= 23){
            if (requestCode == 10) {
                //逻辑：
                //1、如果没有授权，就提示
                //2、如果授权了，就显示操作的按钮
                if (!Settings.canDrawOverlays(this)) {//没有授权
                    Toast.makeText(Test2Activity.this,"not granted", Toast.LENGTH_SHORT);
                } else {//可以绘制Window
                    ll1.setVisibility(View.GONE);
                    ll2.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @OnClick({R.id.btn1,R.id.btn_start})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                requestPermission();
                break;
            case R.id.btn1:
                startActivity(new Intent(mContext,Test1Activity.class));
                break;
        }
    }
}
